import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;

@SuppressWarnings("serial")
public class Plateau extends JComponent {

	public static final int SIZE_CARRE = 20;
	private final int MARGIN_TOP = 6;
	private int height;
	private int width;
    private List<Piece> pieces;
    private List<Rectangle> rects;
	public Plateau(int height, int width) {
		this.height = height;
		this.width = width;
		pieces = new ArrayList<Piece>();
		rects = new ArrayList<Rectangle>();
		setPreferredSize(new Dimension(500, 500));
	}
	
	public void addPiece(Piece p){
		if(p == null){
			throw new IllegalArgumentException();
		}
		pieces.add(p);
	}
	
	public List<Piece> getPieces(){
		return pieces;
	}
	
	public List<Rectangle> getRects(){
		return rects;
	}
	
	public void placePiece(Piece p){
		int i = 0;
		boolean placed = false;
		while(!placed && i < rects.size()){
			Rectangle r = rects.get(i);

			// Place correctement toutes les pièces
			if(p.getRects().get(0).intersects(r)){
				int ajustement = 0;
				if (p.getModel() == Forme.X || p.getModel() == Forme.F) {
					if (r.x < SIZE_CARRE) {
						ajustement = 0;
					} else {
						ajustement = -SIZE_CARRE;
					}
				}

				p.updatePosition(r.x + ajustement);
				p.setY(r.y);
				placed = true;
			}
			i++;
		}
	}
	
	public void paintComponent(Graphics g) {
		g.setColor(Color.WHITE);
		g.fillRect(0, MARGIN_TOP * SIZE_CARRE, width * SIZE_CARRE, height
				* SIZE_CARRE);
		if(rects.size() >= height + MARGIN_TOP * width){
			rects.clear();
		}
		for (int i = MARGIN_TOP; i < height + MARGIN_TOP; i++) {
			for (int j = 0; j < width; j++) {
				g.setColor(Color.black);
				g.drawRect(j * SIZE_CARRE, i * SIZE_CARRE, SIZE_CARRE,
						SIZE_CARRE);
				rects.add(new Rectangle(j * SIZE_CARRE, i * SIZE_CARRE, SIZE_CARRE,
						SIZE_CARRE));
			}
		}

		for(Piece p : pieces){
			placePiece(p);
		}
	}
}
